//
//  DownloaderHelper.m
//  网易公开课项目
//
//  Created by 林 艺 on 13-11-25.
//  Copyright (c) 2013年 Marklin. All rights reserved.
//

#import "DownloaderHelper.h"

#define DOCUMENT_DIRECTORY_PATH (NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0])
@implementation DownloaderHelper

static DownloaderHelper *_instance;

+ (id)shareInstance
{
    if (!_instance)
    {
        _instance = [[DownloaderHelper alloc] init];
    }
    return _instance;
}
- (id)init
{
    self = [super init];
    if (self) {
        _networkQueue = [[ASINetworkQueue alloc] init];
        [_networkQueue setShowAccurateProgress:YES];
        [_networkQueue go];
        _allFilelengthData = [[NSMutableDictionary alloc] init];
        _allReceivedFilelengthData = [[NSMutableDictionary alloc] init];
        
    }
    return self;
}

//创建下载路径
- (NSString *)getVideoDownloadPath
{
    //初始化Documents路径
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    //初始化临时文件路径
    NSString *folderPath = [path stringByAppendingPathComponent:@"Video"];
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断temp文件夹是否存在
    BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
    
    if (!fileExists)
    {//如果不存在创建,因为下载时,不会自动创建文件夹
        [fileManager createDirectoryAtPath:folderPath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
    }
    return folderPath;
}

- (void)clearDatachache
{
    [_allFilelengthData removeAllObjects];
    [_allReceivedFilelengthData removeAllObjects];
}

- (void)startDownload:(NSString *)downloadURL withKey:(NSString *)fileKey
{
    //downloadURL = xxxxxx;
    NSString *fileExtName = [downloadURL lastPathComponent];
    NSString *fileName = [fileExtName stringByDeletingPathExtension];
    
    NSString *downloadPath = [[self getVideoDownloadPath] stringByAppendingPathComponent:fileExtName];
    NSString *tempPath = [[self getVideoDownloadPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", fileName]];
    
    NSURL *url = [NSURL URLWithString:downloadURL];
    ASIHTTPRequest *request =[ASIHTTPRequest requestWithURL:url];
    request.delegate = self;
    [request setDownloadDestinationPath:downloadPath];//设置文件保存路径
    [request setTemporaryFileDownloadPath:tempPath];//设置临时文件路径
    
    [request setShouldContinueWhenAppEntersBackground:YES];
    
    [request setShowAccurateProgress:YES];//显示精确的进度
    
    [request setAllowResumeForFileDownloads:YES];//设置是否支持断点下载
    [request setDownloadProgressDelegate:self];
    [request setUsername:fileKey];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isResume = [fileManager fileExistsAtPath:tempPath];
    
    if (isResume)
    {
        unsigned long long downloadedBytes = [self fileSizeForPath:tempPath];
        if (downloadedBytes > 0)
        {
            NSString *requestRange = [NSString stringWithFormat:@"bytes = %llu-", downloadedBytes];
            [request setRequestMethod:@"GET"];
            NSLog(@"downloadLen %@", requestRange);
            [request addRequestHeader:@"Content-Range" value:requestRange];
        }
    }
    
    [_networkQueue addOperation:request];
    
}

- (void)pauseDownload:(NSString *)fileKey
{
    if ([_networkQueue operationCount] > 0)
    {
        for (int i = 0; i < [_networkQueue operationCount]; i++)
        {
            ASIHTTPRequest *request = [[_networkQueue operations] objectAtIndex:i];
            [request clearDelegatesAndCancel];
        }
    }
}

- (void)requestStarted:(ASIHTTPRequest *)request
{
    
}

- (unsigned long long)fileSizeForPath:(NSString *)path
{
    unsigned long long fileSize = 0;
    NSFileManager *fileManager = [NSFileManager new];//not thread safe
    if ([fileManager fileExistsAtPath:path])
    {
        NSError *_error = nil;
        NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&_error];
        if (!_error && fileDict)
        {
            fileSize = [fileDict fileSize];
        }
    }
    return fileSize;
}

- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
{
    NSString *key = request.username;
    NSLog(@"%@", responseHeaders);
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    float fileLength = 0.0;
    
    NSString *range = [responseHeaders objectForKey:@"Content-Range"];
    
    NSLog(@"%f", [userDefault floatForKey:[NSString stringWithFormat:@"key_%@", key]]);
    
    if (range && ![range isEqualToString:@""])
    {
        fileLength = [userDefault floatForKey:[NSString stringWithFormat:@"key_%@", key]];
    }
    else
    {
        fileLength = [[responseHeaders objectForKey:@"Content-Length"] floatValue];
        [userDefault setFloat:fileLength forKey:[NSString stringWithFormat:@"key_%@", key]];
        [userDefault synchronize];
    }
    NSLog(@"fileLength:%f", fileLength);
    
    [_allFilelengthData setObject:[NSString stringWithFormat:@"%f", fileLength] forKey:key];
    if ([_allReceivedFilelengthData count] > 0)
    {
        [_allReceivedFilelengthData removeObjectForKey:key];
    }
    
    if ([_delegate respondsToSelector:@selector(fileContentLength:key:)])
    {
        [_delegate fileContentLength:fileLength key:key];
    }
    
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSString *key = request.username;
    if ([_delegate respondsToSelector:@selector(requestFinished:key:)])
    {
        [_delegate requestFinished:request.downloadDestinationPath key:key];
        [_allFilelengthData removeObjectForKey:key];
        [_allReceivedFilelengthData removeObjectForKey:key];
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults removeObjectForKey:[NSString stringWithFormat:@"key_%@", key]];
        [userDefaults synchronize];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSString *key = request.username;
    if ([_delegate respondsToSelector:@selector(requestFailed:)])
    {
        [_delegate requestFailed:key];
        [_allReceivedFilelengthData removeObjectForKey:key];
    }
}

- (void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes
{
    NSString *key = request.username;
    float receivedBtye = [[_allReceivedFilelengthData objectForKey:key] floatValue];
    receivedBtye += bytes;
    [_allReceivedFilelengthData setObject:[NSString stringWithFormat:@"%f", receivedBtye] forKey:key];
    
    NSLog(@"receivedBtye:%f", receivedBtye);
    float percent = receivedBtye / [[_allFilelengthData objectForKey:key] floatValue];
    NSLog(@"percent:%.2f", percent);
    
    if (percent >= 1.0)
    {
        percent = 1.0f;
    }
    
    if ([_delegate respondsToSelector:@selector(setProgress:filePath:key:)])
    {
        [_delegate setProgress:percent filePath:request.downloadDestinationPath key:key];
    }
}

@end
